package priv.lhy.ecm.collectorProducer.aftertreatment.reupload.impl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import priv.lhy.ecm.collectorProducer.aftertreatment.reupload.IReupload;
import priv.lhy.ecm.collectorProducer.dal.UploadDataBack;
import priv.lhy.ecm.collectorProducer.service.UploadDataBackServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lihy
 * date: 2019/7/3 10:12
 * description:
 */
@Component("reuploadByDatabase")
public class ReuploadByDatabase implements IReupload {

    @Value("${netty.tcp.host}")
    private String tcpHost;

    @Value("${netty.tcp.port}")
    private int tcpPort;

    @Autowired
    Bootstrap bootstrap;

    @Autowired
    UploadDataBackServiceImpl service;

    @Override
    public void sendMsg() {
        List<UploadDataBack> dataBackList = service.uploadDataBacks();

        List<Long> idList = new ArrayList<>();
        try {
            for (UploadDataBack dataBack : dataBackList) {
                ChannelFuture future = bootstrap.connect(tcpHost, tcpPort).sync();
                Channel channel = future.channel();

                //将上传信息作为附件传递，服务端返回错误可进行后续处理
                AttributeKey<String> msgKey = AttributeKey.valueOf("uploadMsg");
                Attribute<String> msgAttr = channel.attr(msgKey);
                //传递初始上传时间
                AttributeKey<String> argKey = AttributeKey.valueOf("arg");
                Attribute<String> argAttr = channel.attr(argKey);
                msgAttr.set(dataBack.getUploaddata());
                argAttr.set(dataBack.getUploadtime());

                //睡眠10毫秒，防止对服务器造成冲击
                Thread.sleep(10);
                channel.writeAndFlush(dataBack.getUploaddata());
                future.channel().closeFuture().sync();
                idList.add(dataBack.getId());
            }

            service.delRecordsByIds(idList);
        } catch (Exception e) {
            return;
        }
    }
}
